package com.zzf.concurrent.example.design.pattern.read.writer;

import java.util.Arrays;

/**
 * @author GaoFeng2017
 * @date 2019/9/6 20:44
 */
public class ShareData {

    private char[] data;
    private ReadWriterLock readWriterLock;

    public ShareData(int dataSize) {
        this.init(dataSize, true);
    }

    public ShareData(int dataSize, boolean preferWrite) {
        this.init(dataSize, preferWrite);
    }

    private void init(int dataSize, boolean preferWrite) {
        data = new char[dataSize];
        Arrays.fill(data, '*');
        this.readWriterLock = new ReadWriterLock(preferWrite);
    }

    public char[] read() {
        char[] chars = null;
        try {
            readWriterLock.readLock();
            chars = Arrays.copyOf(this.data, this.data.length);
        } finally {
            readWriterLock.readUnLock();
        }
        return chars;
    }

    public void write(char ch) {
        try {
            readWriterLock.writerLock();
            Arrays.fill(data, ch);
        } finally {
            readWriterLock.writerUnLock();
        }
    }
}
